// 个人中心页面JavaScript
document.addEventListener('DOMContentLoaded', function() {
    // 初始化个人中心功能
    initUserProfile();
    
    // 初始化侧边导航
    initSidebarNavigation();
    
    // 初始化表单功能
    initForms();
    
    // 添加动画效果
    addProfileAnimations();
    
    // 加载用户数据
    loadUserData();
});

// 初始化个人中心功能
function initUserProfile() {
    // 绑定上传头像功能
    bindAvatarUpload();
    
    // 绑定修改密码功能
    bindPasswordChange();
    
    // 绑定绑定手机/邮箱功能
    bindAccountBinding();
    
    // 绑定统计数据交互
    bindStatisticsInteraction();
}

// 初始化侧边导航
function initSidebarNavigation() {
    const navItems = document.querySelectorAll('.sidebar-nav-item');
    const contentSections = document.querySelectorAll('.profile-content section');
    
    navItems.forEach(item => {
        item.addEventListener('click', function() {
            // 移除所有活跃状态
            navItems.forEach(i => i.classList.remove('active'));
            
            // 添加当前活跃状态
            this.classList.add('active');
            
            // 获取目标内容ID
            const targetId = this.getAttribute('data-target');
            
            // 隐藏所有内容
            contentSections.forEach(section => {
                section.classList.add('hidden');
            });
            
            // 显示目标内容
            const targetSection = document.getElementById(targetId);
            targetSection.classList.remove('hidden');
            
            // 添加内容切换动画
            targetSection.style.opacity = '0';
            targetSection.style.transform = 'translateX(20px)';
            targetSection.style.transition = 'all 0.3s ease';
            
            setTimeout(() => {
                targetSection.style.opacity = '1';
                targetSection.style.transform = 'translateX(0)';
            }, 10);
        });
    });
}

// 初始化表单功能
function initForms() {
    // 个人信息表单验证
    const personalInfoForm = document.getElementById('personal-info-form');
    if (personalInfoForm) {
        personalInfoForm.addEventListener('submit', function(e) {
            e.preventDefault();
            if (validatePersonalInfoForm()) {
                updatePersonalInfo();
            }
        });
    }
    
    // 密码修改表单验证
    const passwordForm = document.getElementById('password-form');
    if (passwordForm) {
        passwordForm.addEventListener('submit', function(e) {
            e.preventDefault();
            if (validatePasswordForm()) {
                changePassword();
            }
        });
    }
    
    // 绑定手机表单
    const bindPhoneForm = document.getElementById('bind-phone-form');
    if (bindPhoneForm) {
        bindPhoneForm.addEventListener('submit', function(e) {
            e.preventDefault();
            if (validateBindPhoneForm()) {
                bindPhone();
            }
        });
    }
    
    // 绑定邮箱表单
    const bindEmailForm = document.getElementById('bind-email-form');
    if (bindEmailForm) {
        bindEmailForm.addEventListener('submit', function(e) {
            e.preventDefault();
            if (validateBindEmailForm()) {
                bindEmail();
            }
        });
    }
}

// 绑定头像上传功能
function bindAvatarUpload() {
    const avatarUpload = document.getElementById('avatar-upload');
    const avatarPreview = document.getElementById('avatar-preview');
    
    if (avatarUpload) {
        avatarUpload.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                // 检查文件类型
                const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
                if (!validTypes.includes(file.type)) {
                    showToast('请上传有效的图片文件(JPG, PNG, GIF)', 'error');
                    return;
                }
                
                // 检查文件大小
                if (file.size > 5 * 1024 * 1024) { // 5MB
                    showToast('文件大小不能超过5MB', 'error');
                    return;
                }
                
                // 预览图片
                const reader = new FileReader();
                reader.onload = function(event) {
                    avatarPreview.src = event.target.result;
                    showToast('头像已更新，请点击保存按钮确认更改', 'info');
                };
                reader.readAsDataURL(file);
            }
        });
    }
}

// 绑定修改密码功能
function bindPasswordChange() {
    const changePasswordBtn = document.getElementById('change-password-btn');
    if (changePasswordBtn) {
        changePasswordBtn.addEventListener('click', function() {
            // 滚动到密码修改区域
            document.getElementById('account-security').scrollIntoView({ behavior: 'smooth' });
            
            // 切换到密码修改选项卡
            const securityNavItem = document.querySelector('.sidebar-nav-item[data-target="account-security"]');
            if (securityNavItem) {
                securityNavItem.click();
            }
        });
    }
}

// 绑定账号绑定功能
function bindAccountBinding() {
    // 发送手机验证码
    const sendPhoneCodeBtn = document.getElementById('send-phone-code');
    if (sendPhoneCodeBtn) {
        sendPhoneCodeBtn.addEventListener('click', function() {
            const phoneInput = document.getElementById('phone-number');
            if (!phoneInput.value || !validatePhone(phoneInput.value)) {
                showToast('请输入有效的手机号码', 'error');
                return;
            }
            
            // 发送验证码倒计时
            let countdown = 60;
            sendPhoneCodeBtn.disabled = true;
            sendPhoneCodeBtn.textContent = `${countdown}秒后重新发送`;
            
            const timer = setInterval(() => {
                countdown--;
                sendPhoneCodeBtn.textContent = `${countdown}秒后重新发送`;
                
                if (countdown <= 0) {
                    clearInterval(timer);
                    sendPhoneCodeBtn.disabled = false;
                    sendPhoneCodeBtn.textContent = '发送验证码';
                }
            }, 1000);
            
            showToast('验证码已发送', 'success');
        });
    }
    
    // 发送邮箱验证码
    const sendEmailCodeBtn = document.getElementById('send-email-code');
    if (sendEmailCodeBtn) {
        sendEmailCodeBtn.addEventListener('click', function() {
            const emailInput = document.getElementById('email-address');
            if (!emailInput.value || !validateEmail(emailInput.value)) {
                showToast('请输入有效的邮箱地址', 'error');
                return;
            }
            
            // 发送验证码倒计时
            let countdown = 60;
            sendEmailCodeBtn.disabled = true;
            sendEmailCodeBtn.textContent = `${countdown}秒后重新发送`;
            
            const timer = setInterval(() => {
                countdown--;
                sendEmailCodeBtn.textContent = `${countdown}秒后重新发送`;
                
                if (countdown <= 0) {
                    clearInterval(timer);
                    sendEmailCodeBtn.disabled = false;
                    sendEmailCodeBtn.textContent = '发送验证码';
                }
            }, 1000);
            
            showToast('验证码已发送', 'success');
        });
    }
}

// 绑定统计数据交互
function bindStatisticsInteraction() {
    const statsItems = document.querySelectorAll('.stat-item');
    statsItems.forEach(item => {
        item.addEventListener('click', function() {
            const statType = this.getAttribute('data-stat');
            showToast(`查看${getStatLabel(statType)}详情`, 'info');
            
            // 在实际项目中，这里可以跳转到详细的统计页面
        });
    });
    
    // 图表交互
    const chartContainers = document.querySelectorAll('.chart-container');
    chartContainers.forEach(container => {
        container.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-5px)';
            this.style.boxShadow = '0 10px 20px rgba(0, 0, 0, 0.1)';
        });
        
        container.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
            this.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.05)';
        });
    });
}

// 加载用户数据
function loadUserData() {
    // 模拟用户数据
    const userData = {
        name: '张三',
        studentId: '2022001001',
        department: '计算机科学与技术',
        major: '软件工程',
        grade: '2022级',
        phone: '138****6789',
        email: 'zhangsan***@example.com',
        joinDate: '2022-09-01',
        avatar: '../assets/avatar-default.png',
        stats: {
            totalBookings: 42,
            activeBookings: 3,
            completedBookings: 38,
            studyHours: 168,
            favoriteArea: 'A区'
        }
    };
    
    // 填充用户信息
    document.getElementById('user-name').textContent = userData.name;
    document.getElementById('user-student-id').textContent = userData.studentId;
    document.getElementById('avatar-preview').src = userData.avatar;
    
    // 填充表单数据
    document.getElementById('input-name').value = userData.name;
    document.getElementById('input-student-id').value = userData.studentId;
    document.getElementById('input-department').value = userData.department;
    document.getElementById('input-major').value = userData.major;
    document.getElementById('input-grade').value = userData.grade;
    document.getElementById('input-phone').value = userData.phone;
    document.getElementById('input-email').value = userData.email;
    
    // 填充统计数据
    document.querySelector('.stat-total-bookings .stat-number').textContent = userData.stats.totalBookings;
    document.querySelector('.stat-active-bookings .stat-number').textContent = userData.stats.activeBookings;
    document.querySelector('.stat-completed-bookings .stat-number').textContent = userData.stats.completedBookings;
    document.querySelector('.stat-study-hours .stat-number').textContent = userData.stats.studyHours;
    document.querySelector('.stat-favorite-area .stat-value').textContent = userData.stats.favoriteArea;
    
    // 绘制统计图表
    drawStatCharts(userData.stats);
}

// 绘制统计图表
function drawStatCharts(stats) {
    // 模拟图表绘制
    // 在实际项目中，这里可以使用Chart.js等图表库
    
    // 预约统计图表
    const bookingChart = document.querySelector('.booking-chart');
    if (bookingChart) {
        // 模拟图表数据展示
        bookingChart.innerHTML = `
            <div class="chart-placeholder">
                <div class="chart-bar" style="height: ${stats.completedBookings / (stats.totalBookings || 1) * 100}%" title="已完成预约"></div>
                <div class="chart-bar" style="height: ${stats.activeBookings / (stats.totalBookings || 1) * 100}%" title="进行中预约"></div>
            </div>
            <div class="chart-legend">
                <span>已完成: ${stats.completedBookings}</span>
                <span>进行中: ${stats.activeBookings}</span>
            </div>
        `;
    }
    
    // 学习时长图表
    const studyChart = document.querySelector('.study-hours-chart');
    if (studyChart) {
        // 模拟每周学习时长数据
        const weeklyHours = [4, 8, 5, 7, 10, 12, 9];
        let chartBars = '';
        
        weeklyHours.forEach(hours => {
            chartBars += `<div class="chart-bar" style="height: ${hours / 15 * 100}%" title="${hours}小时"></div>`;
        });
        
        studyChart.innerHTML = `
            <div class="chart-placeholder">
                ${chartBars}
            </div>
            <div class="chart-legend">
                <span>本周总时长: ${weeklyHours.reduce((a, b) => a + b)}小时</span>
            </div>
        `;
    }
}

// 表单验证
function validatePersonalInfoForm() {
    const nameInput = document.getElementById('input-name');
    const studentIdInput = document.getElementById('input-student-id');
    
    if (!nameInput.value.trim()) {
        showToast('请输入姓名', 'error');
        nameInput.focus();
        return false;
    }
    
    if (!studentIdInput.value.trim()) {
        showToast('请输入学号', 'error');
        studentIdInput.focus();
        return false;
    }
    
    return true;
}

function validatePasswordForm() {
    const currentPassword = document.getElementById('current-password');
    const newPassword = document.getElementById('new-password');
    const confirmPassword = document.getElementById('confirm-password');
    
    if (!currentPassword.value) {
        showToast('请输入当前密码', 'error');
        currentPassword.focus();
        return false;
    }
    
    if (!newPassword.value) {
        showToast('请输入新密码', 'error');
        newPassword.focus();
        return false;
    }
    
    if (newPassword.value.length < 6) {
        showToast('新密码至少需要6个字符', 'error');
        newPassword.focus();
        return false;
    }
    
    if (newPassword.value !== confirmPassword.value) {
        showToast('两次输入的新密码不一致', 'error');
        confirmPassword.focus();
        return false;
    }
    
    return true;
}

function validateBindPhoneForm() {
    const phoneNumber = document.getElementById('phone-number');
    const phoneCode = document.getElementById('phone-verification-code');
    
    if (!phoneNumber.value || !validatePhone(phoneNumber.value)) {
        showToast('请输入有效的手机号码', 'error');
        phoneNumber.focus();
        return false;
    }
    
    if (!phoneCode.value || phoneCode.value.length !== 6) {
        showToast('请输入6位验证码', 'error');
        phoneCode.focus();
        return false;
    }
    
    return true;
}

function validateBindEmailForm() {
    const emailAddress = document.getElementById('email-address');
    const emailCode = document.getElementById('email-verification-code');
    
    if (!emailAddress.value || !validateEmail(emailAddress.value)) {
        showToast('请输入有效的邮箱地址', 'error');
        emailAddress.focus();
        return false;
    }
    
    if (!emailCode.value || emailCode.value.length !== 6) {
        showToast('请输入6位验证码', 'error');
        emailCode.focus();
        return false;
    }
    
    return true;
}

// 验证函数
function validatePhone(phone) {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
}

function validateEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

// 更新个人信息
function updatePersonalInfo() {
    showToast('正在更新个人信息...', 'info');
    
    setTimeout(() => {
        showToast('个人信息更新成功', 'success');
    }, 1000);
}

// 修改密码
function changePassword() {
    showToast('正在修改密码...', 'info');
    
    setTimeout(() => {
        // 清空表单
        document.getElementById('password-form').reset();
        showToast('密码修改成功，请重新登录', 'success');
        
        // 在实际项目中，这里可以跳转到登录页面
    }, 1000);
}

// 绑定手机
function bindPhone() {
    showToast('正在绑定手机...', 'info');
    
    setTimeout(() => {
        showToast('手机绑定成功', 'success');
        // 更新手机显示
        const phoneNumber = document.getElementById('phone-number').value;
        const maskedPhone = phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
        document.getElementById('input-phone').value = maskedPhone;
    }, 1000);
}

// 绑定邮箱
function bindEmail() {
    showToast('正在绑定邮箱...', 'info');
    
    setTimeout(() => {
        showToast('邮箱绑定成功', 'success');
        // 更新邮箱显示
        const emailAddress = document.getElementById('email-address').value;
        const [username, domain] = emailAddress.split('@');
        const maskedEmail = `${username.substring(0, 3)}***@${domain}`;
        document.getElementById('input-email').value = maskedEmail;
    }, 1000);
}

// 获取统计标签
function getStatLabel(statType) {
    const labelMap = {
        'total': '总预约数',
        'active': '进行中预约',
        'completed': '已完成预约',
        'study': '学习时长',
        'favorite': '常用区域'
    };
    
    return labelMap[statType] || statType;
}

// 添加动画效果
function addProfileAnimations() {
    // 用户卡片动画
    const userCard = document.querySelector('.user-card');
    userCard.style.opacity = '0';
    userCard.style.transform = 'translateY(20px)';
    userCard.style.transition = 'all 0.6s ease';
    
    setTimeout(() => {
        userCard.style.opacity = '1';
        userCard.style.transform = 'translateY(0)';
    }, 300);
    
    // 侧边导航动画
    const navItems = document.querySelectorAll('.sidebar-nav-item');
    navItems.forEach((item, index) => {
        item.style.opacity = '0';
        item.style.transform = 'translateX(-20px)';
        item.style.transition = 'all 0.4s ease';
        
        setTimeout(() => {
            item.style.opacity = '1';
            item.style.transform = 'translateX(0)';
        }, 400 + index * 100);
    });
    
    // 内容区域动画
    const contentSection = document.querySelector('.profile-content > section:not(.hidden)');
    if (contentSection) {
        contentSection.style.opacity = '0';
        contentSection.style.transform = 'translateX(20px)';
        contentSection.style.transition = 'all 0.5s ease';
        
        setTimeout(() => {
            contentSection.style.opacity = '1';
            contentSection.style.transform = 'translateX(0)';
        }, 600);
    }
}

// 添加键盘快捷键
function addKeyboardShortcuts() {
    document.addEventListener('keydown', function(e) {
        // Ctrl/Cmd + S 保存个人信息
        if ((e.ctrlKey || e.metaKey) && e.key === 's') {
            e.preventDefault();
            const personalInfoForm = document.getElementById('personal-info-form');
            if (personalInfoForm && !document.getElementById('personal-info').classList.contains('hidden')) {
                if (validatePersonalInfoForm()) {
                    updatePersonalInfo();
                }
            }
        }
        
        // 数字键1-4切换导航
        if (e.key >= '1' && e.key <= '4') {
            const navItems = document.querySelectorAll('.sidebar-nav-item');
            const index = parseInt(e.key) - 1;
            if (navItems[index]) {
                navItems[index].click();
            }
        }
    });
}

// 初始化键盘快捷键
addKeyboardShortcuts();

// 自适应响应式调整
function adjustResponsiveLayout() {
    const isMobile = window.innerWidth < 768;
    const profileContainer = document.querySelector('.profile-container');
    const sidebar = document.querySelector('.profile-sidebar');
    const content = document.querySelector('.profile-content');
    
    if (isMobile) {
        profileContainer.classList.add('mobile');
        sidebar.classList.add('mobile');
        content.classList.add('mobile');
    } else {
        profileContainer.classList.remove('mobile');
        sidebar.classList.remove('mobile');
        content.classList.remove('mobile');
    }
}

// 监听窗口大小变化
window.addEventListener('resize', debounce(adjustResponsiveLayout, 300));

// 初始化响应式布局
setTimeout(adjustResponsiveLayout, 100);